<template>
  <el-dialog
    title="选择角色"
    :visible.sync="dialogVisible"
    width="70%"
  >
    <div class="app-container">
      <el-row :gutter="10">
        <el-col :span="15">
          <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams">
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                v-model="queryParams.roleName"
                clearable
                placeholder="请输入角色名称"
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">
                搜索
              </el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
                重置
              </el-button>
            </el-form-item>
          </el-form>

          <el-table ref="roleTable" v-loading="loading" :data="roleList"
                    row-key="id"
                    @select="handleSelectionChange"
                    @select-all="handleSelectionChange"
          >
            <el-table-column align="center" type="selection" :reserve-selection="true" />
            <el-table-column label="角色编号" prop="id" />
            <el-table-column :show-overflow-tooltip="true" label="角色名称" prop="roleName" />
            <el-table-column :show-overflow-tooltip="true" label="权限字符" prop="roleKey" />
          </el-table>

          <pagination
            v-show="total>0"
            :limit.sync="queryParams.size"
            :page.sync="queryParams.current"
            :total="total"
            @pagination="getList"
          />
        </el-col>
        <el-col :span="9">
          <p class="title-text pl5">
            已选择角色列表
          </p>
          <el-table border :data="selectedRoleList" max-height="500">
            <el-empty slot="empty" description="暂无选择角色" />
            <el-table-column label="角色编号" prop="id" />
            <el-table-column :show-overflow-tooltip="true" label="角色名称" prop="roleName" />
            <el-table-column
              align="center"
              class-name="small-padding fixed-width"
              label="操作"
            >
              <template slot-scope="scope">
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  type="text"
                  @click="deleteSelectedRoleHandle(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitSelectedRoleHandle">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {pageRole} from '@/api/system/role'
import _ from 'lodash'

export default {
  name: 'RoleChooseTable',
  data() {
    return {
      // 遮罩层
      loading: true,
      dialogVisible: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 用户表格数据
      selectedRoleList: null,
      // 记录默认选中的行Id
      defaultSelectRows: [],
      // 记录被删除的行id 避免分页导致选中状态未被取消
      removedSelectRows: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 显示角色选择弹窗
    showDialog(roleList) {
      this.dialogVisible = true
      // 比较删除掉的
      this.removedSelectRows = _.difference(this.selectedRoleList, roleList).map((item) => item.id)
      this.selectedRoleList = roleList
      // 默认选中
      this.defaultSelectRows = roleList.map((item) => item.id)
      this.$nextTick(() => {
        this.handleDefaultRowSelection()
      })
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      pageRole(this.queryParams).then(
        (response) => {
          this.roleList = response.data.records
          this.total = response.data.total
          this.loading = false
          this.handleDefaultRowSelection()
        }
      )
    },
    handleSelectionChange(selection) {
      this.selectedRoleList = _.uniqBy(selection, 'id')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    deleteSelectedRoleHandle(row) {
      let index = _.findIndex(this.selectedRoleList, ['id', row.id])
      this.selectedRoleList.splice(index, 1)
      let role = this.roleList.find((item) => item.id == row.id)
      this.$refs.roleTable.toggleRowSelection(role, false)
      // 记录 避免不在同一页导致删除失败
      this.removedSelectRows.push(row.id)
    },
    handleDefaultRowSelection() {
      // 比较对象 toggleRowSelection 不是同一个对象不生效。。。
      if (this.defaultSelectRows.length == 0 && this.removedSelectRows.length == 0) {
        return
      }
      this.roleList.forEach((role) => {
        // 设置选中
        let index = this.defaultSelectRows.findIndex((item) => role.id == item)
        if (index !== -1) {
          this.$refs.roleTable.toggleRowSelection(role, true)
          this.defaultSelectRows.splice(index, 1)
        }
        // 取消选中
        let index1 = this.removedSelectRows.findIndex((item) => role.id == item)
        if (index1 !== -1) {
          this.$nextTick(() => {
            this.$refs.roleTable.toggleRowSelection(role, false)
          })
          this.removedSelectRows.splice(index, 1)
        }
      })
    },
    submitSelectedRoleHandle() {
      this.dialogVisible = false
      this.$emit('submit', this.selectedRoleList)
    }
  }
}
</script>
